package actions;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;



import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class RegisterNewUser extends Action {

	
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	{
		try{
			Class.forName("org.postgresql.Driver");
			Connection connect = DriverManager.getConnection("jdbc:postgresql://localhost/135DB?user=postgres&password=admin");
	
		// Store the RowSet in the request scope
		//request.setAttribute("crsStudents", crsStudents);
		
			PreparedStatement prepStmt;
			PreparedStatement prepStmt2;
			PreparedStatement query;
			ResultSet rset;
			
			connect.setAutoCommit(false);
		
			prepStmt = connect.prepareStatement("INSERT INTO users (user_name, password, email) VALUES ('"+request.getParameter("username")+"', md5('"+request.getParameter("password")+"'), '"+request.getParameter("email")+"');");
			prepStmt.executeUpdate();
		
			query = connect.prepareStatement("SELECT last_value FROM users_user_id_seq");
			rset = query.executeQuery();
			String userID = "";
			rset.next();
			userID = rset.getString("last_value");
		
		
			prepStmt2 = connect.prepareStatement("INSERT INTO user_roles (user_ref, user_name, role) VALUES ("+userID+", '"+request.getParameter("username")+"','student');");
			prepStmt2.executeUpdate();
		
			connect.commit();

			return mapping.findForward("success");
		}catch (Exception e){
			e.printStackTrace();
			return null;
		}
	}
}
